package com.jfcloud.mall.user.service.impl;

import com.jfcloud.common.exception.BussinessException;
import com.jfcloud.mall.user.domain.JfcloudUser;
import com.jfcloud.mall.user.domain.dto.DeductForm;
import com.jfcloud.mall.user.persistent.JfcloudUserService;
import com.jfcloud.mall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.Bidi;

/**
 * @author zhaojunfu
 * @Title: UserServiceImpl
 * @ProjectName jfcloud
 * @Description: 账户服务
 * @date 2020/9/1222:26
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private JfcloudUserService jfcloudUserService;

    @Override
    public JfcloudUser deduct(Long userId, DeductForm form) {
        BigDecimal deductValue= form.getValue();
        JfcloudUser user = jfcloudUserService.getById(userId);
        BigDecimal dbValue = user.getAccount();
        if(dbValue.subtract(deductValue).doubleValue()<0){
            throw new BussinessException("用户余额不足");
        }
        user.setAccount(dbValue.subtract(deductValue));
        user.setOrderNum(user.getOrderNum()!=null?user.getOrderNum()+1:1);
        user.setBuyNum(user.getBuyNum()!=null?user.getBuyNum()+form.getProductNum():form.getProductNum());
        user.setBuyAmount(user.getBuyAmount()!=null?user.getBuyAmount().add(form.getValue()):form.getValue());
        jfcloudUserService.saveOrUpdate(user);
        return user;
    }
}
